package cn.itsource.ymcc.producer;

import cn.itsource.ymcc.constant.Constants;
import cn.itsource.ymcc.constant.OrderConstants;
import cn.itsource.ymcc.domain.CourseOrder;
import cn.itsource.ymcc.domain.CourseOrderItem;
import cn.itsource.ymcc.mapper.CourseOrderMapper;
import cn.itsource.ymcc.service.ICourseOrderItemService;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

//保存课程订单以及支付订单的事务消息
@Component
@Slf4j
@RocketMQTransactionListener(
        txProducerGroup = OrderConstants.MQ_COURSEORDER_PAY_GROUP_TRANSACTION
)
public class CourseOrderTransactionListener implements RocketMQLocalTransactionListener {
    @Autowired
    private CourseOrderMapper courseOrderMapper;
    @Autowired
    private ICourseOrderItemService courseOrderItemService;
    @Override
    @Transactional
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object args) {
        try {
            if(message == null || message.getPayload() == null ){
                log.error("事务监听器 拿到的数据有问题 {} ,{}",message);
                return RocketMQLocalTransactionState.ROLLBACK;
            }
            String string = new String((byte[]) message.getPayload(), Constants.UTF8);
            CourseOrder courseOrder = JSONObject.parseObject(string, CourseOrder.class);

            courseOrderMapper.insert(courseOrder);
            List<CourseOrderItem> itemList = courseOrder.getItemList();
            for (CourseOrderItem courseOrderItem : itemList) {
                courseOrderItem.setOrderId(courseOrder.getId());
            }
            courseOrderItemService.saveBatch(itemList);
        }catch (Exception e){
            e.printStackTrace();
            return RocketMQLocalTransactionState.ROLLBACK;//消息不发送
        }
        return RocketMQLocalTransactionState.COMMIT;//消息发送
    }

    /**
     * 检查你本地事务有没有执行成功
     * @param message
     * @return
     */
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        //必须使用订单编号去查询

        //就是去查询数据看数据库有没有数据
        Boolean flag = true;
        if(flag){
            return RocketMQLocalTransactionState.COMMIT;
        }
        return RocketMQLocalTransactionState.ROLLBACK;
    }
}
